import { t } from '@src/locales';
// components
import AddName from './components/addName'
import Chart from './components/chart'
import TaskSearchPanel from './components/taskSearchPanel'
import NoDataViewNew from '@src/component/common/NoDataViewNew';
import _ from 'lodash';

// data
import { SEARCHDATA } from './searchData'


/* Api */
import * as TaskApi from '@src/api/TaskApi.ts';
import * as CustomerApi from '@src/api/CustomerApi.ts';
import * as ReportApi from '@src/api/ReportApi.ts';
import * as ManagementReport from '@src/api/ManagementReport'
import * as PassApi from '@src/api/PassApi'

import { productFieldFix } from '@src/modules/productV2/public.js';
import {
  getProductFields
} from '@src/api/ProductApi';
import { smoothQualityInfoFieldForTable } from '@service/QualityInfoService.ts'
import { formatFields } from '../../productV2/productList/fields';
import {
  CUSTOM_REPORT_GUIDE
} from '@src/component/guide/productV2Store'; // 引导存储
  
import { storageGet, storageSet } from '@src/util/storage'; // 存储方法

import { isOpenData } from '@src/util/platform';

import { isFunction } from '@src/util/type'

// 回执表单过滤字段
const EXPORT_FILTER_FORM_TYPE = ['receiptAttachment', 'serviceIterm', 'systemAutograph', 'sparepart', 'attachment', 'address', 'autograph'];

const STATISTICS_RESOURCE_TYPE = [{
  name:  t('common.base.systemKeyword.task'),
  value: 'task'
}, {
  name: t('common.base.product'),
  value: 'product'
}, {
  name: t('common.base.customer'),
  value: 'client'
}, {
  name: t('report.customReportAggregate.setting4'),
  value: 'custom'
}]

const reportTypeVal = {
  'task': 1,
  'event': 2,
  'product': 3,
  'client': 4,
  'custom': 5
}
const aggregationFetchFuns = {
  '1': 'aggregation',
  '2': 'aggregation',
  '3': 'productAggregation',
  '4': 'customerCustomer',
  '5': 'paasAggregation'
}



export default {
  name: 'custom-report',
  data() {
    return {
      isOpenData,
      reportType: '', // 报表类型
      searchList: [], // 搜索数据
      reportName: {}, // 报表名称 
      chartName: '', // 选中的图表类型
      taskType: '', // 工单类型
      statisticType: '', // 统计指标
      statisticTypeList: [], // 统计指标列表
      taskTypeList: [], // 工单类型列表
      sorts: [], // 排序
      chartList: [], // 图表数据
      parasm: {}, // 条件
      chartTypeId: '', // 
      chartSatet: '',
      editType: '', // 判断是否编辑
      taskParams: {}, // 工单数据搜索条件
      taskView: {}, // 视图参数
      taskFrom: '', // 高级搜索初始化值
      chartType: [{name: t('common.base.table2'), icon: 'icon-detail-fill', id: 1}, {name: t('common.base.histogram'), icon: 'icon-signal-fill', id:2}, {name:t('common.base.lineChart'), icon: 'icon-fund-fill', id:3}, {name: t('common.base.pieChart'), icon: 'icon-piechart-circle-fil', id:4}],
      parentName: '', // 父节点名称
      grayFlag: false, // 灰度，
      statisticResourceTypes: Object.freeze(STATISTICS_RESOURCE_TYPE),
      paasFormTypeTemplateId: '',
      paasFormList: [{
        name: t('report.customReportAggregate.setting5'),
        value: '1'
      }], 
      customId: '',
      loading: false,
      auth: {
        REPORT_EDIT: false,
        REPORT_DELETE: false,
        REPORT_EXPORT: false
      },
      chartLoading: true
    }
  },
  provide(){
    return {
      paasParams: this.paasParams
    }
  },
  computed: {
    paasParams() {
      return {
        paasFormTypeTemplateId: () => this.paasFormTypeTemplateId
      }
    }
  },
  async mounted() {
    let urlParams = {}
    const urlSplitArr = window.location.href.split('?')
    if(urlSplitArr.length > 1) {
      urlSplitArr[1].split('&').forEach(item => {
        urlParams[item.split('=')[0]] = item.split('=')[1]
      })

      this.reportType = urlParams.type
      this.editType = urlParams.edit
      this.parentName = urlParams.parentName;
      this.customId = urlParams.customId
    }

    if(urlParams.type === 'produce' || urlParams.edit) this.loading = true
    await this.fetchEditOrDeleteAuth()

    this.hanldeInitStatisticResourceTypeData(urlParams)

    // this.getGary();
  },
  methods:{
    handleCustomFormChange(val) {
      this.taskType = val
      this.statisticType = ''
      this.field()
      this.fetchPaasFields(val)
      // console.log(this.paasFormType)
    },
    statisticResourceTypeChange(type) {
      this.resetSelectData()
      this.hanldeInitStatisticResourceTypeData()
      this.resetParams()

      if(type === 'custom') this.searchList = []

      for(let [key, val] of Object.entries(reportTypeVal)) {
        if(type === key) {
          this.chartSatet = val
          break;
        }
      }
    },
    resetSelectData() {
      this.statisticType = '';
      this.taskType = '';
      this.paasFormType = ''
      this.paasFormTypeTemplateId = ''
    },
    async fetchAllCustomTemplate() {
      const rs = await ManagementReport.getCustomReportTemplate()
      this.paasFormList = rs.data ?? []
    },
    async  hanldeInitStatisticResourceTypeData(urlParams = {}) {
      if (this.reportType !== 'produce') {
        this.$nextTick(() => {
          setTimeout(() => {
            this.guide()
          }, 500)
        })
      }
  
      if (this.reportType === 'produce' || urlParams.edit) {
        this.taskTypes()
        this.getView()
        await this.reportGet()
        // console.log
        // let chartSatet = this.chartSatet
        // let orderChartSatetFindReportType = ''
        // if(urlParams.edit) {
        //   for(let [key, val] of Object.entries(reportTypeVal)) {
        //     if(chartSatet === val) {
        //       orderChartSatetFindReportType = key
        //       break;
        //     }
        //   }
        // }
        // console.log(orderChartSatetFindReportType)
        // let reportType = urlParams.edit ? this.reportType : orderChartSatetFindReportType
        // this.editPageFetchAdvFields(reportType)
        // if(this.chartSatet === 5) this.fetchAllCustomTemplate()
      } else if (this.reportType === 'task') {
        this.taskTypes()
      } else if (this.reportType === 'product') {
        this.getProductFields()
      } else if(this.reportType === 'client') {
        this.getCustomerFields()
      } else {
        this.fetchAllCustomTemplate()
      }
     
      if(!['produce', 'custom'].includes(this.reportType)) this.field()
    },

    editPageFetchAdvFields(reportType) {
      switch(reportType) {
      case 'task':
        this.taskTypes()
        break;
      case 'product':
        this.getProductFields()
        break;
      case 'client':
        this.getCustomerFields()
        break;
      case 'custom':
        this.fetchAllCustomTemplate()
        break;
      default:
        break;
      }
    },
    // 获取灰度
    async getGary(){
      try{
        const res = await ReportApi.grayFunction();
        if(res.status !== 0) return;

        this.grayFlag = res.data.dashBoardAirp;
      }catch(err){
        console.log(err);
      }
    },
    // 选择图表
    checkChartType(v) {
      this.chartName = v.name; 
      this.chartTypeId = v.id;
      this.$nextTick(() => {
        if (this.$refs.chart) this.$refs.chart.stateText(this.statisticTypeList.filter(item => {return item.label === this.statisticType}))
      })
    },
    // 报表名称
    onSubmit(v) {
      this.reportName = v   
    },
    // 样式
    styles({icon}) {
      let sty;
      if (icon === 'icon-ditu2') {
        sty = 'task-bj9f'
      } else if (icon === 'icon-piechart-circle-fil') {
        sty = 'task-bjf7'
      } else if (icon === 'icon-detail-fill' || icon === 'icon-calendar-fill') {
        sty = 'task-bjc4'
      } else if (icon === 'icon-fund-fill') {
        sty = 'task-bjd1'
      } else {
        sty = 'task-bjc2'
      }
      return sty
    },
    /**
     * @description 获取工单字段列表
     * @return {Promise}
     */
    fetchTaskFields() {
      let params = {
        templateId: this.taskType,
        tableName: 'task',
      };
      return TaskApi.getTaskTemplateFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },
    /**
     * @description 获取工单回执字段列表
     * @return {Promise}
     */
    fetchTaskReceiptFields() {
      let params = {
        templateId: this.taskType,
        tableName: 'task_receipt',
      };
      return TaskApi.getTaskTemplateFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task_receipt';
          field.label = field.displayName;
          field.field = field.fieldName;
        });
        return result;
      });
    },
    // 工单高级搜索参数
    initialize() {
      Promise.all([this.fetchTaskFields(), this.fetchTaskReceiptFields()])
        .then((res) => {
          // 系统字段
          let sys = [...res[0], ...res[1]].filter(item => {
            return item.isSystem && EXPORT_FILTER_FORM_TYPE.indexOf(item.formType) === -1
          })
          // 自定义字段
          let cus = [...res[0], ...res[1]].filter(item => {
            return item.isSearch && !item.isSystem && EXPORT_FILTER_FORM_TYPE.indexOf(item.formType) === -1
          })
          this.seachSet([...sys, ...cus])
        })
        .catch((err) => {
          console.warn(err);
        });
    },
    // 客户高级搜索参数
    async getCustomerFields() {
      try {
        // 获取客户表单字段列表
        let result = await CustomerApi.getCustomerFields({isFromSetting: false});
        if (result.succ) {
          this.searchList = result.data.map(item => {return item});
        }
  
      } catch(err) {
        console.error('customer list get fields error', err);
      }
    },
    // S 产品高级搜索数据
    async getProductFields() {
    // 获取产品动态字段
      try {
        let res = await getProductFields({isFromSetting:false});
        const fields = res.data || []
        fields.forEach(f => {
          if (f.fieldName == 'isRepeatRepair') {
            f.setting.dataSource = [{
              text: this.$t('common.base.all'),
              value: ''
            }, {
              text: this.$t('common.base.yes'),
              value: this.$t('common.base.yes'),
            }, {
              text: this.$t('common.base.no'),
              value: this.$t('common.base.no'),
            }]
          }
        })
        this.productFields(this.smoothProductFields(fields) || [])
      } catch (error) {
        console.error('product-list fetch product fields error', error);
      }
    },

    smoothProductFields (dynamicFields) {
      let fixedFields = _.cloneDeep(productFieldFix);
      if (this.initData?.productConfig?.qrcodeEnabled) {
        fixedFields.push({
          displayName: this.$t('product.type.qrcodeId'),
          fieldName: 'qrcodeId',
          formType: 'text',
          export: false,
          isSystem: 1,
          placeholder: this.$t('product.placeholder.qrcodeId'),
          orderId: 10001,
          tableName: 'product',
        });
      }
      let field = dynamicFields.filter(
        (item) => item.formType == 'customer'
      )[0];
      if (field && field.setting.customerOption?.linkman) {
        fixedFields.push({
          displayName: this.$t('product.detail.catalogView.type.linkman'),
          fieldName: 'linkmanName',
          formType: 'text',
          export: true,
          isSystem: 1,
          tableName: 'product',
        });

        fixedFields.push({
          displayName: this.$t('common.base.phone'),
          fieldName: 'phone',
          export: true,
          isSystem: 1,
          tableName: 'product',
        });
      }

      if (field && field.setting.customerOption?.address) {
        fixedFields.push({
          displayName: this.$t('common.base.locationMap.address'),
          fieldName: 'address',
          export: true,
          formType: 'text',
          isSystem: 1,
          tableName: 'product',
        });
      }

      // .concat([...fixedFields, ...catalogFieldFixForProduct])
      let fields = dynamicFields.concat([...fixedFields])
        .filter(
          (f) =>
            f.formType !== 'separator'
            && f.formType !== 'info'
            && f.formType !== 'autograph'
        )
        .map((f) => {
          // 调整字段顺序
          if (f.fieldName === 'name') {
            f.orderId = -14;
            f.show = true;
          }

          // 新增产品是否重复报修自定义字段 放在产品名称后面
          if (f.fieldName === 'isRepeatRepair') {
            f.orderId = -13;
            f.show = true;
          }

          if (f.fieldName === 'customer') {
            f.orderId = -12;
            f.show = true;
          }

          if (f.fieldName === 'linkmanName') {
            f.orderId = -11;
            f.show = true;
          }

          if (f.fieldName === 'phone') {
            f.orderId = -10;
            f.show = true;
          }

          if (f.fieldName === 'address') {
            f.orderId = -9;
            f.show = true;
          }

          if (f.fieldName === 'serialNumber') {
            f.orderId = -6;
            f.show = true;
          }

          if (f.fieldName === 'type') {
            f.orderId = -5;
            f.show = true;
          }

          if (f.fieldName === 'tags') {
            f.orderId = -8;
          }

          if (f.fieldName === 'productTemplate') {
            f.orderId = -7;
          }

          if (f.fieldName === 'remindCount') {
            f.orderId = -3;
          }

          if (f.fieldName === 'updateTime') {
            f.orderId = -2;
          }

          if (f.fieldName === 'createUser') {
            f.orderId = -1;
            f.show = true;
          }

          if (f.fieldName === 'createTime') {
            f.orderId = 0;
            f.show = true;
          }
          if (f.fieldName === 'catalogId' && f.tableName == 'product') {
            // 转换产品类型表单数据
            f.fieldName = 'pathName'
          }

          // 系统字段默认显示
          f['show'] = f.isSystem ? true : f.show

          return f;
        })
        .sort((a, b) => a.orderId - b.orderId);

      return smoothQualityInfoFieldForTable(fields)
    },
    productFields(dynamicFields) {
      const onlyProductFields = (productFields) => {
        return (
          productFields
            .filter(item => item.tableName == 'product')
            .map(item => { 
              if (item.formType == 'related_catalog') { 
                item.fieldName = 'catalogId' 
              } 
              return item 
            })
        )
      }
      const qrcodeEnabled = this.initData?.productConfig?.qrcodeEnabled || false;
      this.searchList = formatFields(onlyProductFields(dynamicFields), qrcodeEnabled)
    },
    // E 产品高级搜索数据
    // 重置
    resetParams() {
      this.taskParams = {}
      this.taskView = {}
      this.taskFrom = ''
      this.$refs.TaskSearchPanel.hide()
      this.searchList = this.searchList.map(item => {return item})

      if(this.reportType === 'custom' || this.chartSatet === 5) this.$refs?.TaskSearchPanel?.resetFormValue()
      // console.log(this.chartSatet);
      this.$refs?.TaskSearchPanel?.clientCreate()
      if (['task', 'custom', 'product'].includes(this.reportType) || [1, 5, 3].includes(this.chartSatet)) {
        this.aggregation()
      } else {
        this.customerCustomer()
      }
    },
    // 搜索条件
    seachSet(taskFields) {
      let linkman_list = [], address_list = [], product_list = []
      if (taskFields.length) {
        let first = taskFields.filter(item => {
          return item.displayName === this.$t('common.base.customer')
        })[0]
        if (first.setting.customerOption.linkman) {
          linkman_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'tlmName',
            displayName: this.$t('product.detail.catalogView.type.linkman'),
            exportAlias: 'customerLinkman',
            formType: 'select',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            show: true,
            guideProfessions: [],
            isGuideData: false,
            guideData: false,
          }]
        }
        if (first.setting.customerOption.address) {
          address_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'area',
            exportAlias: 'customerAddress',
            displayName: this.$t('common.base.locationMap.area'),
            formType: 'address',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          },
          {
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'cusAddress',
            displayName: this.$t('common.base.locationMap.detail'),
            formType: 'text',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        } 
        if (first.setting.customerOption.product) {
          product_list = [{
            id: 5460,
            tableName: 'customer',
            isSystem: 1,
            fieldName: 'product',
            displayName: this.$t('common.base.product'),
            formType: 'text',
            defaultValue: null,
            isNull: 1,
            isSearch: 1,
            placeHolder: null,
            setting: {},
            orderId: 1,
            isDelete: 0,
            guideProfessions: [],
            show: true,
            isGuideData: false,
            guideData: false,
          }]
        }
      }
      this.searchList = [...taskFields.filter(item => { return item.displayName !== this.$t('common.label.taskNo') && item.formType !== 'attachment'}).map(item => {if (item.fieldName === 'planTime'){item.isNull = 1} return item}), ...linkman_list, ...address_list, ...product_list, ...SEARCHDATA]
    },
    // 搜索
    advancedSearch() {
      const {params, dataView} = this.$refs.TaskSearchPanel.buildParams()
      this.$refs.TaskSearchPanel.hide()
      this.$refs.chart.clons()
      this.taskParams = params
      this.taskView = dataView
      if (['task', 'custom', 'product'].includes(this.reportType) || [1, 5, 3].includes(this.chartSatet) ) {
        this.aggregation()
      } else {
        this.customerCustomer()
      }
    },

    // 创建视图
    async createView() {
      let params = {
        searchModel: Object.keys(this.taskView).length ? JSON.stringify(this.taskView) : '',
        type: this.reportType === 'task' || this.chartSatet === 1 ? 1 : reportTypeVal[this.reportType]
      }
      if (this.editType) params['customId'] = this.customId

      return this.editType ? await ManagementReport.updateView(params) : await ManagementReport.createView(params)
    },
    // 确认是否删除报表
    async delReport() {
      const confirm = await this.$platform.confirm(this.$t('report.customReportAggregate.pla4'))
      if (confirm) {
        this.reportDelete()
      }
    },
    // 引导
    guide() {
      if (storageGet(CUSTOM_REPORT_GUIDE) && storageGet(CUSTOM_REPORT_GUIDE) > 0){
        this.$Guide().destroy(CUSTOM_REPORT_GUIDE)
        return
      } 
      
      this.$Guide([{
        content:this.$t('report.customReportAggregate.title1'),
        haveStep: true,
        nowStep: 1,
        id: 'custom-report-guide',
        domId: 'custom-report-type',
        needCover: true,
        finishBtn: this.$t('common.base.ok'),
        lastFinish: true
      }, {
        content:this.$t('report.customReportAggregate.title2'),
        haveStep: true,
        nowStep: 2,
        id: 'custom-report-guide',
        domId: 'custom-report-condition',
        needCover: true,
        finishBtn: this.$t('common.base.ok'),
        lastFinish: true
      }, {
        content:this.$t('report.customReportAggregate.title3'),
        haveStep: true,
        nowStep: 3,
        id: 'custom-report-guide',
        domId: 'no-data-view-new',
        needCover: true,
        finishBtn: this.$t('common.base.ok'),
        lastFinish: true
      }, {
        content:this.$t('report.customReportAggregate.title4'),
        haveStep: true,
        nowStep: 4,
        id: 'custom-report-guide',
        domId: 'custom-report-submit',
        needCover: true,
        finishBtn: this.$t('common.base.ok'),
      }], 0, '', (e) => {
        return new Promise((resolve, reject) => {
          if (e.type === 'stop') this.chartName = ''
          resolve()
        })
      }).create().then(res_=>{if(res_){
        this.chartName = this.$t('common.base.histogram')
        storageSet(CUSTOM_REPORT_GUIDE, '1')
      }})    
    },
    // 工单类型
    async taskTypes() {
      this.taskTypeList = []
      const {succ, data} = await ReportApi.taskType()
      if (succ) {
        for(let key in data) {
          this.taskTypeList.push({
            value: key,
            label: data[key]
          })
        }
        this.taskTypeList.unshift({
          value: '',
          label: this.$t('common.base.all'),
        })
      }
    },
    // 获取统计指标
    async field(types = '') {
      let type, taskType = this.taskType
      switch (this.reportType) {
      case 'task':
        type = 1
        break;
      case 'client':
        type = 4
        break; 
      case 'product':
        type = 3
        break;    
      case 'custom':
        type = 5
        break; 
      default:
        type = 2
        break;
      }

      const params = {
        type: types || type,
        taskType
      }
      const {code, data} = await ManagementReport.getStatisticsField(params)
      if (code === 200) {
        this.statisticTypeList = data ?? []
        this.chartList = []
        if (this.$refs.chart) this.$refs.chart.clons()
        if (this.statisticType) {
          this.$nextTick(() => {
            if (this.$refs.chart) this.$refs.chart.stateText(this.statisticTypeList.filter(item => {return item.label === this.statisticType}))
          })
        }
        if (this.reportType === 'task') {
          this.initialize()
        }
      }
    },
    // 筛选条件
    checkParam(v) {
      this.sorts = v
      if(!v.sorts) {
        delete this.sorts.sorts
      }
      if (['task', 'custom', 'product'].includes(this.reportType) || [1, 5, 3].includes(this.chartSatet) ) {
        this.aggregation()
      } else {
        this.customerCustomer()
      }
    },
    // 工单搜索
    taskSearc() {
      this.statisticType = ''
      this.field()
    },
    // 统计指标
    statistic() {
      // if (this.reportType === 'task' || this.chartSatet === 1) {
      //   this.aggregation()
      // }
      // else {
      //   this.customerCustomer()
      // }    
      this.aggregation()
      
      this.$nextTick(() => {
        if (this.$refs.chart) this.$refs.chart.stateText(this.statisticTypeList.filter(item => {return item.label === this.statisticType}))
      })
    },
    // 工单：根据关键字查询工单信息
    async aggregation() {
      this.chartLoading = true
      const {taskType, statisticType, sorts, taskParams} = this
      if (!statisticType) {
        this.chartList = [];
        this.chartLoading = false
        return
      }

      this.$loading.service()
      const params = {
        ...sorts,
        ...taskParams,
        templateId: taskType,
        aggregationStr: statisticType
      }
      this.parasm = params
      let fetchFun = 'aggregation'
      if(this.reportType !== 'produce') {
        switch (this.reportType) {
        case 'task':
          fetchFun = 'aggregation'
          break;
        case 'product':
          fetchFun = 'productAggregation'
          break;
        case 'client':
          fetchFun = 'customerCustomer'
          break;
        case 'custom':
          fetchFun = 'paasAggregation'
          params.templateBizId = taskType
          break;
        default:
          fetchFun = 'aggregation'
        }
      } else {
        fetchFun = aggregationFetchFuns[this.chartSatet]
        if(this.chartSatet === 5) params.templateBizId = taskType
      }
      
      if(this.chartSatet === 1) {
        fetchFun = 'aggregation'
      }

      // if(this.reportType === 'client') {
      //   fetchFun = 'customerCustomer'
      // }
      let res = await ReportApi[fetchFun](params)
      this.$loading.service().close()
      if (res.success) {
        if (this.isOpenData && res.result) {
          if (window.WWOpenData?.initCanvas) {
            window.WWOpenData.initCanvas()
            window.WWOpenData.enableCanvasSharing()
          }
          let originItems = res.result || []
          let items = originItems.map(item => {
            return {
              type: 'userName',
              id: item.staffId
            }
          })
          
          const result = await new Promise((resolve, reject) => {
            window.WWOpenData.prefetch({ items }, (err, data) => {
              if (err) {
                return reject(err)
              }
              resolve(data)
            })
          })

          try {
            res.result = originItems.map((item, index) => {
              return Object.assign(item, { name: result.items[index].data })
            })
          } catch (error) {
            console.warn(error)
          }
        }
        this.chartList = res?.result || res?.data || []
        this.chartLoading = false
      }
    },
    // 客户：根据关键字查询客户信息
    async customerCustomer() {

      const {statisticType, sorts, taskParams} = this
      if (!statisticType) {
        this.chartList = []; 
        this.chartLoading = false
        return
      }
      this.$loading.service()
      this.chartLoading = true
      const params = {
        ...sorts,
        ...taskParams,
        aggregationStr: statisticType
      }
      this.parasm = params
      let res = await ReportApi.customerCustomer(params)
      this.$loading.service().close()
      if (res.success) {
        if (this.isOpenData && res.result) {
          if (window.WWOpenData?.initCanvas) {
            window.WWOpenData.initCanvas()
            window.WWOpenData.enableCanvasSharing()
          }
          let originItems = res.result || []
          let items = originItems.map(item => {
            return {
              type: 'userName',
              id: item.staffId
            }
          })
          
          const result = await new Promise((resolve, reject) => {
            window.WWOpenData.prefetch({ items }, (err, data) => {
              if (err) {
                return reject(err)
              }
              resolve(data)
            })
          })

          try {
            res.result = originItems.map((item, index) => {
              return Object.assign(item, { name: result.items[index].data })
            })
          } catch (error) {
            console.warn(error)
          }
        }
        this.chartList = res.result.map(item => {return item})
        this.chartLoading = false
      }    
    },
    // 创建报表
    async reportCreate() {

      this.$loading.service()
      const res = await this.createView()
      
      const {reportName, reportType, chartTypeId, taskType, statisticType, sorts, taskParams} = this
      let sort = sorts ? sorts : {}
      // let type = 0
      let params = {
        type: reportTypeVal[reportType] ?? '',
        chartName: reportName.name,
        chartDesc: reportName.textarea,
        reportKey: reportName.reportKey,
        aggregationStr: statisticType,
        viewId: res.data,
        chartType: chartTypeId,
        taskType,
        searchModel: JSON.stringify(taskParams),
        ...sort
      }
      if (this.editType) params['customId'] = this.customId

      const { msg, code, data, message, status} = this.editType ? await ManagementReport.reportUpdate(params) : await ManagementReport.reportCreate(params)
      
      // // 过滤编辑 + 灰度
      // if(this.grayFlag){
      // try{
      //   if(data){
      //     const customeId = this.cusomeId
      //     const reportThemeData = await ReportApi.insertReportTheme({
      //       parentName: decodeURI(this.parentName),
      //       reportName: reportName.name,
      //       customId: this.editType ? customeId : data,
      //       reportIcon: chartTypeId,
      //       textArea: reportName.textarea
      //     })
      //   }
      // }catch(err){
      //   console.log('ReportApi.insertReportTheme', err);
      // }
      // }:
      this.$loading.service().close()
      if(code === 200 ) this.$platform.toast(this.editType ? this.$t('common.base.saveSuccess') : this.$t('common.base.tip.createSuccess'), 'success')

      // 失败结果被修改：失败返回 status: 1, message: ...
      if (status && status !== 0) return this.$platform.alert(message)

      const upType = this.editType ? 'edit' : 'add';
      let customId = this.editType ? this.customId : data;
      this.getParent({type: upType, customId});

      if(isFunction(window?.parent?.flashSomePage)) {
        window?.parent?.flashSomePage([{
          type: 'M_DASHBOARD_TJBB',
        }]);
      }

      setTimeout(()=> {
        window.location.href = `${this.$resourcePrefix}/stats/customReportAggregate?type=produce&customId=${ this.editType ? this.customId : data}`;
      }, 600);

    },
    // 获取指定的的自定义报表
    async reportGet() {
      // this.loading = true
      try {
        
        // if(this.reportType === 'produce') {
        // // 获取权限
        //   await this.fetchEditOrDeleteAuth()
        // }

        const params = {
          customId: this.customId
        }
        const {data} = await ManagementReport.reportGet(params)

        this.reportName = {
          name: data.chartName,
          textarea: data.chartDesc,
          reportKey: data.reportKey
        }
        
        this.statisticType = data.aggregationStr
        this.taskType = data.taskType
        this.sorts = data.sortJson ? JSON.parse(data.sortJson) : ''
        this.chartSatet = data.type
        this.chartTypeId = data.chartType
        this.paasFormTypeTemplateId = data.taskType
        this.taskParams = JSON.parse(data.searchModel)
        await this.field(data.type)
        // this.reportType 
        switch (data.chartType) {
        case 1:
          this.chartName = this.$t('common.base.table2')
          break;
        case 2:
          this.chartName = this.$t('common.base.histogram')
          break; 
        case 3:
          this.chartName = this.$t('common.base.lineChart')
          break;     
        default:
          this.chartName = this.$t('common.base.pieChart')
          break;
        }
        
        // type 1工单、2事件、3产品、4客户报表
        if (data.type == 4) {
          await this.getCustomerFields()
          this.customerCustomer()
        } else if (data.type === 1) {
          await this.initialize()
          this.aggregation()
        } else if (data.type === 3) {
          await this.getProductFields()
          this.aggregation()
        } else if(data.type === 5) {
          this.taskParams.templateBizId = data.taskType
          this.taskParams.pageNum = 1
          this.taskParams.aggregationValueName = data.taskType
          await this.fetchPaasFields(data.taskType)
          this.aggregation()
        } else {
          this.aggregation()
        }
        if(data.type === 5) this.fetchAllCustomTemplate()

        this.loading = false
      } catch (e) {
        console.log('[error]', e)
        this.loading = false
      }
    },
    // 获取自定义视图
    async getView() {
      const params = {
        customId: this.customId
      }
      const { code, data, msg} = await ManagementReport.getView(params)
      if(code !== 200) this.$platform.alert(msg)
      this.taskFrom = JSON.parse(data.searchModel || '{}')
      this.taskView = JSON.parse(data.searchModel || '{}')
    },
    // 删除报表
    async reportDelete() {
      const params = {
        customId: this.customId
      }
      const {message, data, code } = await ManagementReport.reportDelete(params)

      // 报表权限控制 + 灰度
      // if(this.grayFlag){
      //   try {
      //     if(result){
      //       const customId = this.customId
      //       const delData = await ReportApi.deleteReportTheme(customId);
      //     }
      //   }catch(err){
      //     console.log('ReportApi.deleteReportTheme', err);
      //   }
      // }

      if(code !== 200 )this.$platform.alert(this.$t('common.base.deleteFail'));

      if(isFunction(window?.parent?.flashSomePage)) {
        window.parent.flashSomePage([{
          type: 'M_DASHBOARD_TJBB',
        }]);
      }
   
      this.getParent({ type: 'del' });
      // let id = window.frameElement.dataset.id
      // return this.$platform.closeTab(id)
    },
    // 编辑
    editChares() {
      let reportType = ''
      for(let [key, val] of Object.entries(reportTypeVal)) {
        // console.log(key, val)
        if(val === this.chartSatet) reportType = key
      }
      
      let type = this.chartSatet === 1 ? 'task' : reportType
      
      // if(this.grayFlag){
      //   window.location.href = `/stats/customReport?type=${type}&edit=1&parentName=${this.parentName}`
      // }else {
      //   window.location.href = `/stats/customReport?type=${type}&edit=1`;
      // }
      window.location.href = `${this.$resourcePrefix}/stats/customReportAggregate?type=${type}&edit=1&customId=${this.customId}`;
    },
    async fetchPaasFields(templateBizId) {
      const rs = await PassApi.getFormFieldListInfo({
        templateBizId
      })
      const { paasFormFieldVOList = [], systemFormFieldVOList = [] } = rs?.data ?? {}

      // const systemFields = systemFormFieldVOList.map(field => {
      //   return {
      //     ...field,
      //     fieldName: SystemFieldNameEnum[field.fieldName] || field.fieldName,
      //     formType: SystemFieldNameEnum[field.fieldName]  === ''
      //   };
      // });

      const paasAdvField = [...paasFormFieldVOList].filter(item => item.isSearch === 1);
      this.searchList = paasAdvField
    },

    async fetchEditOrDeleteAuth() {
      const rs = await ReportApi.getReportAggregateAuth()
      this.auth = rs.auths ?? {}
    },
    // 让父页面刷新数据 不出意外的话这个页面只会出现在 fe-foundation-engine项目 路径/stats/intelligenceReport/charts
    getParent(type){
      try{ 
        if(isFunction(window?.parent?.postMessage)) {
          window.parent.$setChildFun(type);
        }
      }catch(e) {
        console.log('@getParent', e)
      }
    }
  },
  components: {
    [AddName.name]: AddName,
    [Chart.name]: Chart,
    [NoDataViewNew.name]: NoDataViewNew,
    [TaskSearchPanel.name]: TaskSearchPanel
  }
}
